package com.example.newheze;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.BottomNavigationView;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.newheze.Control.ControlActivity;
import com.example.newheze.FieldMessage.MessageActivity;
import com.example.newheze.FieldMessage.Sendcommand;
import com.example.newheze.User.UserActivity;
import com.example.newheze.vo.Data;
import com.example.newheze.vo.Dtu;
import com.example.newheze.vo.JsonData;

import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends MyActivity implements AdapterView.OnItemSelectedListener {
    //-----------------------
    //选择作物功能
    private Spinner crop_spinner;
    private Spinner period_spinner;
    private List<String> crop_list;
    private List<String> period_list;
    private ArrayAdapter crop_adapter;
    private ArrayAdapter period_adapter;
    private TextView soil_range;
    private TextView co2_range;
    private String crop=null;
    private String period=null;
    private String file_dtu1_crop="1.txt";
    private String file_dtu1_period="2.txt";
    private String file_dtu2_crop="3.txt";
    private String file_dtu2_period="4.txt";
    //-----------------------

    private double soilhumi_1;
    private double soilhumi_2;
    private double coo2;

    private String content;
    private  int n_crop;
    private int n_period;




    private TextView mTextMessage;
    private Handler handler;
    private TextView textView;
    private Dtu dtu=new Dtu();
    private Data data=new Data();
    private TextView soilhumi1;
    private TextView soilhumi2;
    private TextView airtemp;
    private TextView airhumi;
    private TextView sundata;
    private TextView coo;
    private TextView dangqian;
    private Button qiehuan;
    private Button shuaxin;
    Calendar cal;
    String year;
    String day;
    String month;
    String minute;
    String second;
    String my_time;
    String hour;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {


        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    setTitleName(getResources().getString(R.string.title_home));
                    MessageActivity messageActivity=new MessageActivity();
                    fragmentTransaction.replace(R.id.fragment,messageActivity);
                    fragmentTransaction.commit();

                    return true;
                case R.id.navigation_dashboard:
                    setTitleName(getResources().getString(R.string.title_dashboard));
                    ControlActivity longRangeControl=new ControlActivity();
                    fragmentTransaction.replace(R.id.fragment,longRangeControl);
                    fragmentTransaction.commit();

                    return true;
                case R.id.navigation_notifications:
                    setTitleName(getResources().getString(R.string.title_notifications));
                    UserActivity userActivity=new UserActivity();
                    fragmentTransaction.replace(R.id.fragment,userActivity);
                    fragmentTransaction.commit();

                    return true;
            }
            return false;
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    protected void setRootView() {
        super.setRootView();
        setContentView(R.layout.activity_fieldmessage);
        Window window = this.getWindow();
        soilhumi1 = findViewById(R.id.soilhumi11);
        soilhumi2 = findViewById(R.id.soilhumi22);
        airtemp = findViewById(R.id.airtemp);
        airhumi = findViewById(R.id.airhumi);
        sundata = findViewById(R.id.sundata);
        coo = findViewById(R.id.coo);
        dangqian = findViewById(R.id.dangqian);
        shuaxin = findViewById(R.id.shuaxin);
        qiehuan = findViewById(R.id.qiehuan);
        shuaxin.setOnClickListener(this);
        qiehuan.setOnClickListener(this);
        textView=findViewById(R.id.time);
        //-----------------------
        soil_range=(TextView) findViewById(R.id.soil_range);
        co2_range=(TextView) findViewById(R.id.co2_range);
        crop_spinner=(Spinner)findViewById(R.id.crop_spinner);
        period_spinner=(Spinner)findViewById(R.id.period_spinner);
        //textView.setText("您选择的作物是草莓");
        //设置数据源
        crop_list=new ArrayList<String>();
        crop_list.add("草莓");
        crop_list.add("番茄");
        crop_list.add("黄瓜");
        period_list=new ArrayList<String>();
        period_list.add("缓苗期");
        period_list.add("初花期");
        period_list.add("结果期");
        //新建数组适配器
        crop_adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,crop_list);
        period_adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,period_list);
        //设置下拉列表样式
        crop_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        period_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //spinner加载适配器
        crop_spinner.setAdapter(crop_adapter);
        period_spinner.setAdapter(period_adapter);
        //spinner设置监听器
        crop_spinner.setOnItemSelectedListener(this);
        period_spinner.setOnItemSelectedListener(this);

        //read1();
        // read2();

        getData();

        //-----------------------

        setTime();
        //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        //设置状态栏颜色
        window.setStatusBarColor(getResources().getColor(R.color.color_green700));

        mTextMessage = (TextView) findViewById(R.id.message);
//        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
//        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
//
//        //初始化导航栏
//        FragmentManager fragmentManager = getFragmentManager();
//        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//        MessageActivity messageActivity=new MessageActivity();
//        fragmentTransaction.replace(R.id.fragment,messageActivity);
////        getData();
//        fragmentTransaction.commit();

    }

    private void showMyDialog(int flag){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setIcon(R.drawable.ku);
        builder.setTitle("温馨提示");
        if(flag==0)
            builder.setMessage("Co²浓度不在合适范围内！");
        if(flag==1)
            builder.setMessage("土壤湿度1浓度不在合适范围内！");
        if(flag==2)
            builder.setMessage("土壤湿度2浓度不在合适范围内！");
        builder.setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        AlertDialog dialog=builder.create();
        dialog.show();
    }








    @Override
    protected void initWidght() {
        super.initWidght();
        setTitleName("当前数据");//title
//                  setTitleBack(false,R.mipmap.ic_search);//有图标，但不是返回
        //setTitleBack(true,0);//返回
//                  setTitleRightText("保存");//右侧文字

        showTitleRes(R.id.title_choose);//扩展menu（图标）
        //goneTitleRes(R.id.title_add);隐藏图标，一般用不到
    }
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.qiehuan){
            // workFragment.titleSearch();
            textView.setText("正在获取数据");
            if(dtu.getDtu().equals("031")){
                dangqian.setText("当前大棚：2");
                dtu.setDtu("032");

                n_crop= read(0,file_dtu2_crop);
                crop= crop_list.get(n_crop);

                n_period=  read(1,file_dtu2_period);
                period=period_list.get(n_period);
                //setRange();

                list_click(2);
                Toast.makeText(MainActivity.this, "正在获取，请稍后", Toast.LENGTH_SHORT).show();
            }
            else {
                dtu.setDtu("031");
                dangqian.setText("当前大棚：1");


                n_crop= read(0,file_dtu1_crop);
                crop= crop_list.get(n_crop);

                n_period=  read(1,file_dtu1_period);
                period=period_list.get(n_period);


               // setRange();
                list_click(1);

                Toast.makeText(MainActivity.this, "正在获取，请稍后", Toast.LENGTH_SHORT).show();
            }
            getData();
            setTime();
        }
        else if(v.getId() ==  R.id.shuaxin){
            if(true){
                textView.setText("正在获取数据");
                Toast.makeText(MainActivity.this, "正在发送指令，请等待10秒", Toast.LENGTH_SHORT).show();
                sendMessage();
            }
            setTime();
        }
    }
    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()){
            case R.id.title_choose://添加
                break;
            case R.id.choose_one://大棚1
                Toast.makeText(this,"大棚1",Toast.LENGTH_SHORT).show();
                dtu.setDtu("031");
//                getData();
                break;
            case R.id.choose_two://大棚2
                Toast.makeText(this,"大棚2",Toast.LENGTH_SHORT).show();
                dtu.setDtu("032");
//                getData();
                break;
            case R.id.refresh:
//                sendMessage();
                break;
        }
        return super.onMenuItemClick(item);
    }
    public void getData(){
        String address="http://202.194.131.174:8080/ghs/getdata";
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("limit",1);
            jsonObject.put("currentPage",1);
            jsonObject.put("hoursetype",dtu.getDtu());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        sendRequestWithOkHttp(address, jsonObject);
    }

    private void list_click(final int flag){


    }
    private void sendRequestWithOkHttp(final String address,  final JSONObject jsonObject){
        new Thread(new Runnable() {
            @Override
            public void run() {
                MediaType JSONObject = MediaType.parse("application/json; charset=utf-8");
                RequestBody requestBody = RequestBody.create(JSONObject, jsonObject.toString());
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(address).post(requestBody).build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        setResult(e.getMessage(),false);
                        Log.i("cuowu",e.getMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String responseData = response.body().string();
                        setResult(responseData,true);
                        Log.i("message",responseData.toString());
                    }
                });
            }
        }).start();
    }

    private void setResult(final String msg,final boolean success){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(success){
                    try {
                        FragmentManager fragmentManager = getFragmentManager();
                        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                        JSONObject jsonObject = new JSONObject(msg);
                        JsonData jsonData = new JsonData(jsonObject.getString("msg"),new JSONArray(jsonObject.getString("rows")),jsonObject.getString("success"),jsonObject.getString("total"));
                        JSONArray jsonArray = jsonData.getRows();
                        if(jsonArray == null) {
                            Toast.makeText(MainActivity.this, "当前数据库没有数据", Toast.LENGTH_SHORT).show();
                        }
                        else {
                            JSONObject jsonObject1 = jsonArray.getJSONObject(0);
                            Log.i("soilhumi1", jsonObject1.getString("soilhumi1"));
                            data = new Data(jsonObject1.getString("soilhumi1"), jsonObject1.getString("soilhumi2"), jsonObject1.getString("airtemp"), jsonObject1.getString("airhumi"), jsonObject1.getString("sundata"), jsonObject1.getString("coo"));
                            if (data.getSoilhumi1().equals("null"))
                                data.setSoilhumi1("0");
                            if (data.getSoilhumi2().equals("null") )
                                data.setSoilhumi2("0");
                            if (data.getAirhumi().equals("null") )
                                data.setAirhumi("0");
                            if (data.getAirtemp().equals("null") )
                                data.setAirtemp("0");
                            if (data.getSundata().equals("null") )
                                data.setSundata("0");
                            if (data.getCoo().equals( "null"))
                                data.setCoo("0");

                            soilhumi1.setText(data.getSoilhumi1());
                            soilhumi_1=Double.valueOf(data.getSoilhumi1());
                            soilhumi2.setText(data.getSoilhumi2());
                            soilhumi_2=Double.valueOf(data.getSoilhumi2());
                            airtemp.setText(data.getAirtemp());
                            airhumi.setText(data.getAirhumi());
                            sundata.setText(data.getSundata());
                            coo.setText(data.getCoo());
                            coo2=Double.valueOf(data.getCoo());





                            Log.i("我想要的大棚号啊啊啊",dtu.getDtu());


                            if(dtu.getDtu()=="031")
                            { n_crop= read(0,file_dtu1_crop);
                                crop= crop_list.get(n_crop);

                                n_period=  read(1,file_dtu1_period);
                                period=period_list.get(n_period);
                                //setRange();
                            }
                            else if(dtu.getDtu()=="032"){
                                n_crop= read(0,file_dtu2_crop);
                                crop= crop_list.get(n_crop);

                                n_period=  read(1,file_dtu2_period);
                                period=period_list.get(n_period);
                                //setRange();
                            }
                            //  save(i,file_dtu2_crop);



                            crop_spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){

                                @Override
                                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

                                    crop= crop_list.get(i);
                                    setRange();
                                    Log.i("!!!!!!!","已存入");
                                    if(dtu.getDtu()=="031")
                                        save(i,file_dtu1_crop);
                                    if(dtu.getDtu()=="032")
                                    save(i,file_dtu2_crop);

                                    //Log.i("作物",crop);
                                    //textView.setText("您选择的作物是"+crop);

                                }

                                @Override
                                public void onNothingSelected(AdapterView<?> adapterView) {

                                }
                            });


                            period_spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){

                                @Override
                                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                    period=period_list.get(i);
                                    setRange();
                                    //save2(i);
                                    Log.i("生长期",period);
                                    Log.i("作物",crop);
                                    Log.i("Co²浓度",data.getCoo());
                                    Log.i("土壤湿度1",data.getSoilhumi1());
                                    Log.i("土壤湿度2",data.getSoilhumi2());


                                    if(dtu.getDtu()=="031")
                                        save(i,file_dtu1_period);
                                    if(dtu.getDtu()=="032")
                                        save(i,file_dtu2_period);

                                }

                                @Override
                                public void onNothingSelected(AdapterView<?> adapterView) {

                                }
                            });


                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                else{
                    Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                }
            }


        });



    }
    private void setRange(){
        if(crop=="草莓"&&period=="缓苗期") {soil_range.setText("65—70%"); co2_range.setText("1200—1400ppm");
            if(soilhumi_1<65||soilhumi_1>70)
            {
                showMyDialog(1);


            }
            if(soilhumi_2<65||soilhumi_2>70)  {
                showMyDialog(2);
            }

        }
        if(crop=="草莓"&&period=="初花期") {soil_range.setText("80—85%"); co2_range.setText("1200—1400ppm");
            if(soilhumi_1<80||soilhumi_1>85)
            {
                showMyDialog(1);

            }
            if(soilhumi_2<80||soilhumi_2>85)  {
                showMyDialog(2);
            }



        }
        if(crop=="草莓"&&period=="结果期") {soil_range.setText("80—85%"); co2_range.setText("1200—1400ppm");

            if(soilhumi_1<80||soilhumi_1>85)
            {
                showMyDialog(1);

            }
            if(soilhumi_2<80||soilhumi_2>85)  {
                showMyDialog(2);
            }


        }
        if(crop=="番茄"&&period=="缓苗期") {soil_range.setText("75—80%"); co2_range.setText("1200—1400ppm");

            if(soilhumi_1<75||soilhumi_1>80)
            {
                showMyDialog(1);
            }
            if(soilhumi_2<75||soilhumi_2>80)  {
                showMyDialog(2);
            }


        }
        if(crop=="番茄"&&period=="初花期") {soil_range.setText("75—85%"); co2_range.setText("1200—1400ppm");

            if(soilhumi_1<75||soilhumi_1>85)
            {
                showMyDialog(1);

            }
            if(soilhumi_2<75||soilhumi_2>85)  {
                showMyDialog(2);
            }


        }
        if(crop=="番茄"&&period=="结果期") {soil_range.setText("75—85%"); co2_range.setText("1200—1400ppm");
            if(soilhumi_1<75||soilhumi_1>85)
            {
                showMyDialog(1);

            }
            if(soilhumi_2<75||soilhumi_2>85)  {
                showMyDialog(2);
            }


        }
        if(crop=="黄瓜"&&period=="缓苗期") {
            soil_range.setText("70—85%"); co2_range.setText("1200—1400ppm");
            if(soilhumi_1<70||soilhumi_1>85)
            {
                showMyDialog(1);

            }
            if(soilhumi_2<70||soilhumi_2>85)  {
                showMyDialog(2);
            }}
        if(crop=="黄瓜"&&period=="初花期") {soil_range.setText("70—85%"); co2_range.setText("1200—1400ppm");
            if(soilhumi_1<70||soilhumi_1>85)
            {
                showMyDialog(1);

            }
            if(soilhumi_2<70||soilhumi_2>85)  {
                showMyDialog(2);
            }


        }
        if(crop=="黄瓜"&&period=="结果期") {soil_range.setText("75—85%"); co2_range.setText("1200—1400ppm");


            if(soilhumi_1<75||soilhumi_1>85)
            {
                showMyDialog(1);

            }
            if(soilhumi_2<75||soilhumi_2>85)  {
                showMyDialog(2);
            }

        }


        if(coo2>1400||coo2<1200){
            showMyDialog(0);

        }
    }

    private void sendMessage(){
        String command = null;
        Toast.makeText(MainActivity.this, "正在发送指令，请等待10秒", Toast.LENGTH_SHORT).show();
        if(dtu.getDtu().equals("031"))
            command = "BB00dongping001EF";
        else command = "BB00dongping002EF";
        new Thread(new Sendcommand(handler, command)).start();
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Toast.makeText(this, "指令发送成功", Toast.LENGTH_SHORT).show();
        getData();
    }
    private void setTime(){
        cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        month = String.valueOf(cal.get(Calendar.MONTH)+1);
        day = String.valueOf(cal.get(Calendar.DATE));
        if (cal.get(Calendar.AM_PM) == 0)
            hour = String.valueOf(cal.get(Calendar.HOUR));
        else
            hour = String.valueOf(cal.get(Calendar.HOUR)+12);
        minute = String.valueOf(cal.get(Calendar.MINUTE));
        second = String.valueOf(cal.get(Calendar.SECOND));

        my_time =month + "月" + day+"日 "+hour+"时"+minute+"分";
        textView.setText(my_time);
        // workFragment.titleSearch();
    }
    private void save(int i,String fileName) {

        try {

            FileOutputStream outputStream = openFileOutput(fileName,
                    Activity.MODE_PRIVATE);
            outputStream.write(String.valueOf(i).getBytes());
            outputStream.flush();
            outputStream.close();
            //Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_LONG).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }



    private int read(int flag,String fileName) {
        int result=0;
        try {

            FileInputStream inputStream = this.openFileInput(fileName);
            byte[] bytes = new byte[1024];
            ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
            while (inputStream.read(bytes) != -1) {
                arrayOutputStream.write(bytes, 0, bytes.length);
            }
            inputStream.close();
            arrayOutputStream.close();
            content = new String(arrayOutputStream.toByteArray());
            Log.i("文件内容1",String.valueOf(content.toCharArray()[0])+"测试");

                if (flag == 0){
                    if(content==null){
                        result=0;
                    }else{
                        result=Integer.parseInt(String.valueOf(content.toCharArray()[0]));
                    }
                    crop_spinner.setSelection(result);
                   }
                if (flag == 1){
                    if(content==null){
                        result=0;
                    }else{
                        result=Integer.parseInt(String.valueOf(content.toCharArray()[0]));
                    }
                    period_spinner.setSelection(result);
                }

                //showTextView.setText(content);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }
}